import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

// 创建 axios 实例
const service = axios.create({
  baseURL: '/app/ky_black/admin',
  timeout: 30000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    // 如果有 token，添加到请求头
    if (userStore.token) {
      config.headers['Authorization'] = `Bearer ${userStore.token}`
    }
    
    // 处理请求参数
    if (config.params) {
      // 移除空参数
      const cleanParams = {}
      Object.keys(config.params).forEach(key => {
        const value = config.params[key]
        if (value !== '' && value !== undefined && value !== null) {
          cleanParams[key] = value
        }
      })
      config.params = cleanParams
    }
    
    return config
  },
  error => {
    console.error('请求错误：', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data

    // 如果返回的不是 blob 数据（文件下载）
    if (!(response.config.responseType && response.config.responseType === 'blob')) {
      // 这里可以根据后端的响应结构调整
      if (res.code !== 0) {
        ElMessage({
          message: res.msg || '请求失败',
          type: 'error',
          duration: 5 * 1000
        })

        // 处理特定的错误码
        if (res.code === 401) {
          // token 过期或未登录
          ElMessageBox.confirm(
            '登录状态已过期，请重新登录',
            '系统提示',
            {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            const userStore = useUserStore()
            userStore.logout()
            window.location.reload()
          })
        }
        return Promise.reject(new Error(res.msg || '请求失败'))
      }
      return res
    }
    return response
  },
  error => {
    console.error('响应错误：', error)
    const { response } = error
    let message = '服务器错误'

    if (response && response.data) {
      message = response.data.msg || '请求失败'
    }

    ElMessage({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 封装 GET 请求
service.get = (url, params, config = {}) => {
  return service({
    method: 'get',
    url,
    params,
    ...config
  })
}

// 封装 POST 请求
service.post = (url, data, config = {}) => {
  return service({
    method: 'post',
    url,
    data,
    ...config
  })
}

// 封装 PUT 请求
service.put = (url, data, config = {}) => {
  return service({
    method: 'put',
    url,
    data,
    ...config
  })
}

// 封装 DELETE 请求
service.delete = (url, data, config = {}) => {
  return service({
    method: 'delete',
    url,
    data,
    ...config
  })
}

export default service 